#############################################################################
# Copyright (c) 2009 Dmitry Grushin <dgrushin@gmail.com>.
#
# This file is part of clupower (cluster power manager utility)
#
# Clupower is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Clupower is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Clupower.  If not, see <http://www.gnu.org/licenses/>.
#
# Contributors:
#    Dmitry Grushin <dgrushin@gmail.com> - initial API and implementation
#############################################################################

require 'socket'

class WakeOnLan
  attr :socket

  def initialize
		@socket=UDPSocket.open()
		@socket.setsockopt(Socket::SOL_SOCKET,Socket::SO_BROADCAST,1)
	end;

	def close
    @socket.close
    @socket=""
  end

	def wake(mac_addr, broadcast="", ip_addr="")
		wol_magic=(0xff.chr)*6+(mac_addr.split(/:/).pack("H*H*H*H*H*H*"))*16
		if broadcast==""
			ips=ip_addr.split(/\./)
      c=ips[0].to_i
			if c<=127; ips[1]="255";end # class A:1--127
			if c<=191; ips[2]="255";end # class B:128--191
			if c<=223; ips[3]="255";end # class C:192--223
			# class D:224--239 multicast
			broadcast=ips.join(".")
		end
		3.times{ @socket.send(wol_magic,0,broadcast,"discard") }
	end
end
